import 'dart:convert';

import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:detect/notifier/location.dart';
import 'package:detect/utils/extensions.dart';
import 'package:detect/utils/global.dart';
import 'package:detect/utils/modal_util.dart';
import 'package:detect/utils/toast_util.dart';
import 'package:detect/widgets/loading_widget.dart';
import 'package:provider/provider.dart';

class AMapMarker extends MarkerOption {
  final void Function(IMarker iMarker, String object)? onTap;

  AMapMarker({
    String? data,
    required dynamic id,
    required super.coordinate,
    super.opacity,
    super.anchorU = .5,
    super.anchorV = 1,
    super.widget,
    this.onTap,
  }) : super(
          infoWindowEnabled: false,
          object: jsonEncode({'id': id, 'data': data ?? ''}),
        );
}

class AMap extends StatelessWidget {
  final MapType mapType;
  final double zoomLevel;
  final LatLng? centerCoordinate;
  final List<AMapMarker>? markers;
  final void Function(LatLng latLng)? onMapClicked;
  final void Function(AmapController controller)? onMapCreated;

  const AMap({
    super.key,
    this.mapType = MapType.Standard,
    this.zoomLevel = 15,
    this.centerCoordinate,
    this.markers,
    this.onMapClicked,
    this.onMapCreated,
  });

  @override
  Widget build(BuildContext context) => AmapView(
        showZoomControl: false,
        showCompass: false,
        showScaleControl: false,
        zoomGesturesEnabled: true,
        scrollGesturesEnabled: true,
        rotateGestureEnabled: true,
        tiltGestureEnabled: true,
        zoomLevel: zoomLevel,
        mapType: mapType,
        markers: markers,
        centerCoordinate: centerCoordinate,
        maskDelay: const Duration(seconds: 1),
        mask: const LoadingWidget(desc: "地图加载中"),
        onMarkerClicked: (iMarker) async {
          String object = await iMarker.object;
          if (object.isNotEmpty) {
            Map<String, dynamic> markerObject = jsonDecode(object);
            AMapMarker? marker = markers?.find((element) {
              Map<String, dynamic> itemObject = jsonDecode(element.object!);
              return itemObject['id'] == markerObject['id'];
            });
            marker?.onTap?.call(iMarker, object);
          }
        },
        onMapClicked: (latLng) {
          FocusManager.instance.primaryFocus?.unfocus();
          onMapClicked?.call(latLng);
        },
        onMapCreated: (controller) async {
          controller.setMinZoomLevel(zoomLevel);
          controller.setMaxZoomLevel(18);
          controller.setZoomByCenter(true);
          onMapCreated?.call(controller);
        },
      );

  ///选择位置
  static Future<LatLng?> choosePoint(BuildContext context) {
    LatLng? point;
    AmapController? mapController;
    return ModalUtil.dialog<LatLng>(
      context: context,
      child: Stack(
        children: [
          Positioned(
            left: 0,
            top: 0,
            right: 0,
            bottom: 0,
            child: AMap(
              zoomLevel: 15,
              mapType: MapType.Standard,
              centerCoordinate: context.read<LocationNotifier>().latLng,
              onMapClicked: (latlng) {
                mapController?.clear();
                mapController?.addMarker(AMapMarker(
                  id: DateTime.now().microsecondsSinceEpoch,
                  coordinate: latlng,
                  widget: Icon(Icons.place, color: ColorUtil.color("#10BEFF"), size: Global.ds(40)),
                ));
                point = latlng;
              },
              onMapCreated: (controller) {
                controller.setMinZoomLevel(15);
                mapController = controller;
              },
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              color: Colors.white,
              padding: EdgeInsets.all(Global.ds(15)),
              child: TextButton(
                onPressed: () {
                  if (point == null) {
                    ToastUtil.msg("请点击地图选择位置");
                  } else {
                    Navigator.pop(context, point);
                  }
                },
                style: TextButton.styleFrom(
                  foregroundColor: Colors.white,
                  backgroundColor: ColorUtil.color("#10BEFF"),
                  fixedSize: Size.fromHeight(Global.ds(44)),
                  textStyle: TextStyle(fontSize: Global.ds(16)),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.horizontal(left: Radius.circular(Global.ds(22)), right: Radius.circular(Global.ds(22))),
                  ),
                ),
                child: const Text("确认选择"),
              ),
            ),
          )
        ],
      ),
    );
  }
}
